package com.csun.cmny.provider.controller;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.constant.OldInConstant;
import com.csun.cmny.provider.dto.CacOldManDto;
import com.csun.cmny.provider.dto.CacOldManQueryDto;
import com.csun.cmny.provider.model.dto.CacOldmanDto;
import com.csun.cmny.provider.model.dto.SendMessageRequest;
import com.csun.cmny.provider.model.dto.user.UserRoleDto;
import com.csun.cmny.provider.model.vo.RpcUserVo;
import com.csun.cmny.provider.pojo.CacOldman;
import com.csun.cmny.provider.pojo.CacOldmanMinor;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.*;
import com.csun.cmny.provider.utils.DateUtil;
import com.csun.cmny.provider.vo.CacEvaluateOldManVo;
import com.csun.cmny.provider.vo.Page;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/*
 * 社区老人评估
 * */
@RestController
@RequestMapping("/CacOldman")
public class CacOldmanController extends BaseController {
    @Autowired
    private CacOldmanService cacOldmanService;
    @Autowired
    private CacOldmanMinorService cacOldmanMinorService;
    @Resource
    private UacRpcService uacRpcService;
    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Resource
    private OpcMessageService opcMessageService;
    @Resource
    private OmcRpcService omcRpcService;

    /*
     * 这里的认证和当前登录的用户注解先预留，等完善了再进行修改
     * 1.判断该用户是否属于该机构人员
     * */
    //新增老人评估
    @RequestMapping(value = "/addCacOldman", method = RequestMethod.POST)
    public Wrapper addCacOldman(CacOldman cacOldman) {
        //校验
      /*  if (StringUtils.isEmpty(cacOldman.getCacNo())) {
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"评估编号不能为空",null);
        }*/
      /*  if (cacOldman.getCacType() == null) {
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"评估类别不能为空",null);
        }*/
        if (cacOldman.getOldmanId() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.old.man.id.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getEgname())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.egname.is.not.null", null), null);
        }
        if (cacOldman.getPreGrade() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.pre.grade.is.not.null", null), null);
        }
        if (cacOldman.getLevelCareId() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.old.man.final.grade.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getEvaluator())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.evaluate.name.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getEvaluatorSignDate())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.evaluate.time.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getVideoId())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.video.id.is.not.ull", null), null);
        }
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        cacOldman.setHomeId(loginAuthDto.getGroupId().intValue());
        //判断是否已经存在

        /*
        * 2020-07-29
        * xcr
        * 二次入院
        * 关闭初评校验
        * */
//        Map<String, Object> queryMap = new HashMap<>();
//        //queryMap.put("cacType",cacOldman.getCacType());
//        queryMap.put("oldmanId", cacOldman.getOldmanId());
//        List<Map<String, Object>> mapList = cacOldmanService.showAll(queryMap);
//        if (!CollectionUtils.isEmpty(mapList)) {
//            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("cac.old.man.is.exist", null), 0);
//        }

        //新增
        int cacId = cacOldmanService.insert(cacOldman);
        if (cacId <= 0) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.add.fail", null), 0);
        }

        //修改omc老人表数据（评估等级） 社区版评估完成后设置老人状态为 【待缴费】
        CacOldmanDto cacOldmanDto = new CacOldmanDto();
        cacOldmanDto.setOldmanId(cacOldman.getOldmanId().longValue());
        cacOldmanDto.setCacType(cacOldman.getCacType());
        cacOldmanDto.setLevelCareId(cacOldman.getLevelCareId());
        cacOldmanDto.setLevelCareName(cacOldman.getLevelCareName());
        cacOldmanDto.setStatus(OldInConstant.DAIJIAOFEI);
        int ret = omcRpcService.updateOldmanByEvaluate(cacOldmanDto);
//
//        //创建推送请求对象 老人入院评估完成
//        SendMessageRequest sendMessageRequest = new SendMessageRequest();
//        sendMessageRequest.setMsgCode(OldInConstant.IN_FLOW_EVALUATE_COMPLETE);
//        sendMessageRequest.setGroupId(loginAuthDto.getGroupId());
//        opcMessageService.pushWithMsgCode(sendMessageRequest);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.add.success", null), cacId);
    }

    //根据id删除  1-删除老人关联的与小项的数据 2-删除老人评估数据
    @RequestMapping(value = "/delCacOldman", method = RequestMethod.POST)
    public Wrapper delCacOldman(Integer cacId) {
        if (cacId == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.id.is.not.null", null), null);
        }
        //删除老人和小项的关系数据
        CacOldmanMinor cacOldmanMinor = new CacOldmanMinor();
        cacOldmanMinor.setCacId(cacId);
        int n = cacOldmanMinorService.delByOidAndCacId(cacOldmanMinor);
        //删除老人的评估记录
        int m = cacOldmanService.deleteByCacId(cacId);
        if (m <= 0) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.delete.fail", null), n);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.delete.success", null), n);
    }

    //修改老人评估
    @RequestMapping(value = "/updateCacOldman", method = RequestMethod.POST)
    public Wrapper updateCacOldman(CacOldman cacOldman) {
        //校验
        if (cacOldman.getCacId() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.id.is.not.null", null), null);
        }
        if (cacOldman.getOldmanId() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.old.man.id.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getEgname())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.egname.is.not.null", null), null);
        }
        if (cacOldman.getPreGrade() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.pre.grade.is.not.null", null), null);
        }
        if (cacOldman.getLevelCareId() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.old.man.final.grade.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getEvaluator())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.evaluate.name.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getEvaluatorSignDate())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.evaluate.time.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getVideoId())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.video.id.is.not.ull", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getEgnameSignDate())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.egname.sign.date", null), null);
        }
        int n = cacOldmanService.update(cacOldman);
        if (n <= 0) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.update.fail", null), 0);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.update.success", null), n);
    }

    //根据评估id查询评估数据
    @RequestMapping(value = "/selectByCacId", method = RequestMethod.POST)
    public Wrapper selectByCacId(Integer cacId) {
        if (cacId == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.id.is.not.null", null), null);
        }
        //返回的结果集
        Map<String, Object> dataMap = new HashMap<>();
        //查询老人评估记录数据
        CacOldman cacOldman = cacOldmanService.selectByCacId(cacId);
        if (cacOldman == null) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("cac.is.not.exist", null), 0);
        }
        dataMap.put("cacOldman", cacOldman);
        //获取资源路径集
        if (StringUtils.isEmpty(cacOldman.getVideoId())) {
            dataMap.put("videoList", new ArrayList<>());
        } else {
            String[] video = cacOldman.getVideoId().split("-");
            List<String> videoList = new ArrayList<>();
            //循环根据资源id查询视频资源
            for (int i = 0; i < video.length; i++) {
                //执行查询语句
                String videoUrl = video[i];//待完善
                videoList.add(videoUrl);
            }
            dataMap.put("videoList", videoList);
        }
        //查询老人与小项的数据
        CacOldmanMinor cacOldmanMinor = new CacOldmanMinor();
        cacOldmanMinor.setCacId(cacId);
        List<Map<String, Object>> oldmanMinList = cacOldmanMinorService.selectCacOldMnr(cacOldmanMinor);
        if (CollectionUtils.isEmpty(oldmanMinList)) {
            dataMap.put("oldmanMinList", new ArrayList<>());
        } else {
            dataMap.put("oldmanMinList", oldmanMinList);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.query.success", null), dataMap);
    }

    //查询该机构的老人评估记录
    @RequestMapping(value = "/showAll", method = RequestMethod.POST)
    public Wrapper showAll(@RequestBody Map<String, Object> queryMap) {
        String pageNo = (String) queryMap.get("pageNo");
        String pageSize = (String) queryMap.get("pageSize");

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        //当前登录用户获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        queryMap.put("homeId", homeId);
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<Map<String, Object>> mapList = cacOldmanService.showAll(queryMap);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
        if (CollectionUtils.isEmpty(mapList)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("cac.data.is.null", null), 0);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.query.success", null), pageInfo);
    }

    /**
     * 查询老人评估详情
     *
     * @return
     */
    @RequestMapping(value = "/getCacOldmanInfo", method = RequestMethod.POST)
    public Wrapper<List<Map<String, Object>>> getCacOldmanInfo(@RequestBody Map<String, Object> queryMap) {
        List<Map<String, Object>> mapList = cacOldmanService.getCacOldmanInfo(queryMap);
        //return WrapMapper.ok(mapList);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), mapList);
    }

    /**
     * 查询评估员角色的用户
     *
     * @return
     */
    @RequestMapping(value = "/selectEvaluator", method = RequestMethod.POST)
    public Wrapper selectEvaluator() {
        UserRoleDto dto = new UserRoleDto();
        //dto.setRoleCode("nursing");
        dto.setGroupId(getLoginAuthDto().getGroupId());
        dto.setRoleCode("evaluate");//评估员角色code
        List<RpcUserVo> list = uacRpcService.queryUserListByRoleCodeAndGroupId(dto);
        //return WrapMapper.ok(list);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), list);
    }

    /**
     * 根据评估状态和老人姓名模糊查询老人信息
     *
     * @return CacOldManDto cacOldManDto
     */
    @RequestMapping(value = "/selectByName", method = RequestMethod.POST)
    public Wrapper selectByName(@RequestBody CacOldManDto cacOldManDto) {
        cacOldManDto.setGroupId(getLoginAuthDto().getGroupId());
        List<CacEvaluateOldManVo> list = cacOldmanService.showByType(cacOldManDto);
        //return WrapMapper.ok(list);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null), list);
    }

    @RequestMapping(value = "/addCacOldmanWc", method = RequestMethod.POST)
    public Wrapper addCacOldmanWc(CacOldman cacOldman) {
        //日期正则表达式 yyyy-MM-dd
        String pattern = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])"
                + "|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|"
                + "[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";

        //校验
        if (cacOldman.getCacType() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.old.man.type.is.not.null", null), null);
        }
        if (cacOldman.getOldmanId() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.old.man.id.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getEgname())) {//武昌版,该字段为非传,但数据库表为必填
            cacOldman.setEgname(getLoginAuthDto().getUserName());//登录人的名字
        }
        if (cacOldman.getPreGrade() == null) {//武昌版,该字段为非传,但数据库表为必填
            cacOldman.setPreGrade(0);
        }
        if (cacOldman.getLevelCareId() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.old.man.final.grade.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getEvaluator())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.evaluate.name.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getEvaluatorSignDate()) && !Pattern.matches(pattern, cacOldman.getEvaluatorSignDate())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.evaluate.time.is.not.null", null), null);
        }
        if (StringUtils.isEmpty(cacOldman.getVideoId())) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.video.id.is.not.ull", null), null);
        }
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        cacOldman.setHomeId(loginAuthDto.getGroupId().intValue());
        //判断初评是否已经存在
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("cacType", cacOldman.getCacType());
        queryMap.put("homeId", getLoginAuthDto().getGroupId());
        queryMap.put("oldmanId", cacOldman.getOldmanId());
        List<Map<String, Object>> mapList = cacOldmanService.showAll(queryMap);
        if (cacOldman.getCacType() == 1) {
            /**
             * @author  chisj
             * @date    2019-11-16
             * @desc    老人可多次入院，有多条初评记录
             */
//            if (!CollectionUtils.isEmpty(mapList)) {
//                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("cac.old.man.record.is.exist", null), 0);
//            }
            //创建推送请求对象 老人入院评估完成
            SendMessageRequest sendMessageRequest = new SendMessageRequest();
            sendMessageRequest.setMsgCode(OldInConstant.IN_FLOW_EVALUATE_COMPLETE);
            sendMessageRequest.setGroupId(loginAuthDto.getGroupId());
            opcMessageService.pushWithMsgCode(sendMessageRequest);

        } else {//添加常规评估和及时评估时,必须已有初评并且评估时间不能小于初评评估时间
            //查询老人初评记录
            CacOldManDto dto = new CacOldManDto();
            dto.setGroupId(getLoginAuthDto().getGroupId());
            dto.setOldManId(cacOldman.getOldmanId().longValue());
            dto.setEvaluateType(1);//1.初评
            List<CacEvaluateOldManVo> list = cacOldmanService.showAllWithPage(dto);
            if (null != list && list.size() > 0) {//跟初评评估时间进行比较
                CacEvaluateOldManVo cacEvaluateOldManVo = list.get(0);
                try {
                    int days = DateUtil.differentDays(DateUtil.getDate(cacEvaluateOldManVo.getEvaluatorSignDate()), DateUtil.getDate(cacOldman.getEvaluatorSignDate()));
                    if (days < 0) {
                        return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("cac.date.is.error", null), 0);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            } else {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("cac.old.man.record.is.not.exist", null), 0);
            }
        }

        //新增
        int cacId = cacOldmanService.insert(cacOldman);
        if (cacId <= 0) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("comment.add.fail", null), 0);
        }

        //修改omc老人表数据（评估等级） 武昌版初评后 老人状态为【已评估】
        CacOldmanDto cacOldmanDto = new CacOldmanDto();
        cacOldmanDto.setOldmanId(cacOldman.getOldmanId().longValue());
        cacOldmanDto.setCacType(cacOldman.getCacType());
        cacOldmanDto.setLevelCareId(cacOldman.getLevelCareId());
        cacOldmanDto.setStatus(OldInConstant.YIPINGGU);
        int ret = omcRpcService.updateOldmanByEvaluate(cacOldmanDto);

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.add.success", null), cacId);
    }

    /**
     * 分页按老人姓名查询评估记录
     *
     * @param cacOldManQueryDto
     * @return
     */
    @RequestMapping(value = "/showAllWithPage", method = RequestMethod.POST)
    public Wrapper showAllWithPage(@RequestBody CacOldManQueryDto cacOldManQueryDto) {
        CacOldManDto cacOldManDto = new CacOldManDto();
        //当前登录用户获取机构id
        cacOldManDto.setGroupId(getLoginAuthDto().getGroupId());
        cacOldManDto.setOldName(cacOldManQueryDto.getOldName());
        cacOldManDto.setOldIdCard(cacOldManQueryDto.getOldIdCard());
        cacOldManDto.setEvaluateType(1);//初评 分页查询只查询初评状态的评估
        List<CacEvaluateOldManVo> list = cacOldmanService.listTheLastestEvaluateRecord(cacOldManDto);
        //分页数据
        Page pageObject = new Page(cacOldManQueryDto.getPageNum(), cacOldManQueryDto.getPageSize(), list);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.query.success", null), pageObject);
    }

    /**
     * 根据老人ID查询老人评估状态,也可以加上评估状态查询该老人该评估的最新数据
     *
     * @param cacOldManDto
     * @return
     */
    @RequestMapping(value = "/queryByOldManId", method = RequestMethod.POST)
    public Wrapper queryByOldManId(CacOldManDto cacOldManDto) {
        //校验
        if (cacOldManDto.getOldManId() == null) {
            return WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, cmnyMessageSource.getMessage("cac.old.man.id.not.null", null), null);
        }
        cacOldManDto.setGroupId(getLoginAuthDto().getGroupId());
        //查询评估记录
        CacEvaluateOldManVo cacEvaluateOldManVo = null;
        List<CacEvaluateOldManVo> list = cacOldmanService.showAllWithPage(cacOldManDto);
        if (null != list && list.size() > 0) {
            cacEvaluateOldManVo = list.get(0);
        } else {
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("cac.data.is.null", null), null);
        }
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource.getMessage("comment.query.success", null), cacEvaluateOldManVo);
    }


}
